package com.veepeak.server.service;

import com.google.common.collect.Maps;
import com.veepeak.server.common.BaseRepository;
import com.veepeak.server.common.BaseService;
import com.veepeak.server.domain.DtcCommand;
import com.veepeak.server.dto.PageModel;
import com.veepeak.server.repository.DtcCommandRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class DtcCommandService extends BaseService<DtcCommand,String> {
    @Autowired
    private DtcCommandRepository dtcCommandRepository;

    @Override
    public BaseRepository<DtcCommand, String> getRepo() {
        return this.dtcCommandRepository;
    }

    public DtcCommand getDtc(String pid){
        return dtcCommandRepository.getFirstByPid(pid);
    }

    public Page<DtcCommand> datatables(int page,int size, String search){
        if (StringUtils.isBlank(search)){
            return dtcCommandRepository.findAll(PageRequest.of(page,size));
        }else{
            return dtcCommandRepository.findByPidIsLikeOrderByPid(PageRequest.of(page,size),"%"+search+"%");
        }
    }

    public Map<String, String> upload(List<DtcCommand> uploadList) {
        long insertCount = 0;
        long updateCount = 0;
        for (DtcCommand dtc : uploadList){
            DtcCommand dtcCommand = dtcCommandRepository.getFirstByPid(dtc.getPid());
            if ( dtcCommand == null ){
                dtcCommandRepository.save(dtc);
                insertCount++;
            }else{
                dtcCommand.setDescription(dtc.getDescription());
                dtcCommandRepository.save(dtcCommand);
                updateCount++;
            }
        }
        Map<String,String> result = Maps.newHashMap();
        result.put("insert",String.valueOf(insertCount));
        result.put("update",String.valueOf(updateCount));
        return result;
    }
}
